package nju.bishe.weibo.ui.base;

import nju.bishe.weibo.AboutDialog;
import nju.bishe.weibo.LaunchActivity;
import nju.bishe.weibo.LoginActivity;
import nju.bishe.weibo.PreferencesActivity;
import nju.bishe.weibo.R;
import nju.bishe.weibo.TwitterActivity;
import nju.bishe.weibo.TwitterApplication;
import nju.bishe.weibo.data.db.FollowerDatabase;
import nju.bishe.weibo.data.db.TwitterDatabase;
import nju.bishe.weibo.data.db.UserInfoDatabase;
import nju.bishe.weibo.service.TwitterService;
import nju.bishe.weibo.util.ImageManager;
import nju.bishe.weibo.util.Preferences;
import weibo4android.User;
import weibo4android.Weibo;
import weibo4android.WeiboException;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.MediaColumns;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;

/**
 * A BaseActivity has common routines and variables for an Activity that
 * contains a list of tweets and a text input field.
 * 
 * Not the cleanest design, but works okay for several Activities in this app.
 */

public class BaseActivity extends Activity {

	private static final String TAG = "BaseActivity";

	protected SharedPreferences mPreferences;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		_onCreate(savedInstanceState);
	}

	// 因为onCreate方法无法返回状态，因此无法进行状态判断，
	// 为了能对上层返回的信息进行判断处理，我们使用_onCreate代替真正的
	// onCreate进行工作。onCreate仅在顶层调用_onCreate。
	protected boolean _onCreate(Bundle savedInstanceState) {

		// PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
		mPreferences = TwitterApplication.mPref; // PreferenceManager.getDefaultSharedPreferences(this);

		// manageUpdateChecks();

		// No Titlebar
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		requestWindowFeature(Window.FEATURE_PROGRESS);

		return true;

	}

	public TwitterDatabase getDb() {
		return TwitterApplication.mDb;
	}

	public FollowerDatabase getFollowerDb() {
		return TwitterApplication.fDb;
	}

	public UserInfoDatabase getUserInfoDb() {
		return TwitterApplication.uDb;
	}

	public Weibo getApi() {
		return TwitterApplication.mApi;
	}

	public SharedPreferences getPreferences() {
		return mPreferences;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	protected boolean isLoggedIn() {
		return (getApi().getUserId() != null);

	}

	private static final int RESULT_LOGOUT = RESULT_FIRST_USER + 1;

	// Retrieve interface

	public ImageManager getImageManager() {
		return TwitterApplication.mImageManager;
	}

	public void logout() {

		// getDb().clearData();
		// getApi().reset();
		// Clear SharedPreferences
		// SharedPreferences.Editor editor = mPreferences.edit();
		// editor.clear();
		// editor.commit();
		TwitterService.unschedule(this);
		// TwitterApplication.mProfileImageCacheManager.getImageManager().clear();

		Dialog dialog = new AlertDialog.Builder(BaseActivity.this)
				.setMessage("你确定退出吗？")
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						Intent i_back=new Intent();
						   i_back.putExtra("finish", true);
						   i_back.setClass(BaseActivity.this, LoginActivity.class);
						   i_back.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						   startActivity(i_back);
						 
					}
				})
				.setNeutralButton("取消", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.dismiss();
					}
				}).create();// 创建按钮

		// 显示对话框
		dialog.show();

	}

	protected void manageUpdateChecks() {
		boolean isEnabled = mPreferences.getBoolean(
				Preferences.CHECK_UPDATES_KEY, false);

		if (isEnabled) {
			TwitterService.schedule(this);
		} else {
			TwitterService.unschedule(this);
		}
	}

	// Menus.

	protected static final int OPTIONS_MENU_ID_LOGOUT = 1;
	protected static final int OPTIONS_MENU_ID_PREFERENCES = 2;
	protected static final int OPTIONS_MENU_ID_ABOUT = 3;
	protected static final int OPTIONS_MENU_ID_SEARCH = 4;
	protected static final int OPTIONS_MENU_ID_REPLIES = 5;
	protected static final int OPTIONS_MENU_ID_DM = 6;
	protected static final int OPTIONS_MENU_ID_TWEETS = 7;
	protected static final int OPTIONS_MENU_ID_TOGGLE_REPLIES = 8;
	protected static final int OPTIONS_MENU_ID_FOLLOW = 9;
	protected static final int OPTIONS_MENU_ID_UNFOLLOW = 10;
	protected static final int OPTIONS_MENU_ID_IMAGE_CAPTURE = 11;
	protected static final int OPTIONS_MENU_ID_PHOTO_LIBRARY = 12;
	protected static final int OPTIONS_MENU_ID_INVITE = 13;

	/**
	 * 如果增加了Option Menu常量的数量，则必须重载此方法， 以保证其他人使用常量时不产生重复
	 * 
	 * @return 最大的Option Menu常量
	 */
	protected int getLastOptionMenuId() {
		return OPTIONS_MENU_ID_PHOTO_LIBRARY;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		MenuItem item;
		item = menu.add(0, OPTIONS_MENU_ID_PREFERENCES, 0,
				R.string.omenu_settings);
		item.setIcon(android.R.drawable.ic_menu_preferences);

		item = menu.add(0, OPTIONS_MENU_ID_LOGOUT, 0, R.string.omenu_signout);
		item.setIcon(android.R.drawable.ic_menu_close_clear_cancel);

		item = menu.add(0, OPTIONS_MENU_ID_ABOUT, 0, R.string.omenu_about);
		item.setIcon(android.R.drawable.ic_menu_info_details);

		item = menu.add(0, OPTIONS_MENU_ID_INVITE, 0, R.string.invite);
		item.setIcon(R.drawable.invite);

		return true;
	}

	protected static final int REQUEST_CODE_LAUNCH_ACTIVITY = 0;
	protected static final int REQUEST_CODE_PREFERENCES = 1;

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case OPTIONS_MENU_ID_LOGOUT:
			logout();
			return true;
		case OPTIONS_MENU_ID_SEARCH:
			onSearchRequested();
			return true;
		case OPTIONS_MENU_ID_PREFERENCES:
			Intent launchPreferencesIntent = new Intent().setClass(this,
					PreferencesActivity.class);
			startActivityForResult(launchPreferencesIntent,
					REQUEST_CODE_PREFERENCES);
			return true;
		case OPTIONS_MENU_ID_ABOUT:
			AboutDialog.show(this);
			return true;
		case OPTIONS_MENU_ID_INVITE:
			invite();
			return true;
		}

		return super.onOptionsItemSelected(item);
	}

	protected void launchActivity(Intent intent) {
		// TODO: probably don't need this result chaining to finish upon logout.
		// since the subclasses have to check in onResume.
		startActivityForResult(intent, REQUEST_CODE_LAUNCH_ACTIVITY);
	}

	protected void launchDefaultActivity() {
		Intent intent = new Intent();
		intent.setClass(this, TwitterActivity.class);
		startActivity(intent);
	}

	private String getRealPathFromURI(Uri contentUri) {
		String[] proj = { MediaColumns.DATA };
		Cursor cursor = managedQuery(contentUri, proj, null, null, null);
		int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == REQUEST_CODE_PREFERENCES && resultCode == RESULT_OK) {
			manageUpdateChecks();
		} else if (requestCode == REQUEST_CODE_LAUNCH_ACTIVITY
				&& resultCode == RESULT_LOGOUT) {
			Log.i(TAG, "Result logout.");

		}
	}

	protected boolean checkIsLogedIn() {
		/*
		 * if (!getApi().isLoggedIn()) { Log.i(TAG, "Not logged in.");
		 * handleLoggedOut(); return false; }
		 */
		return true;
	}

	protected void invite() {
		User profileInfo;// 用户信息
		String msg;
		try {
			Log.i(TAG, "Invite by message");
			profileInfo = getApi().verifyCredentials();
			msg = "Hi," + "\n" + "我正在使用新浪微博" + "\n" + "我的昵称是"
					+ profileInfo.getName() + "\n" + "我的网页是"
					+ profileInfo.getURL() + "\n" + "快来关注我吧" + "\n"
					+ "该用户通过android客户端：【南大微博控】 发送";

			Uri smsToUri = Uri.parse("smsto:123456");
			Intent sendIntent = new Intent(Intent.ACTION_VIEW, smsToUri);

			sendIntent.putExtra("sms_body", msg);

			sendIntent.setType("vnd.android-dir/mms-sms");

			startActivity(sendIntent);
		} catch (WeiboException e) {

			e.printStackTrace();
		}
	}

}
